/* eslint-disable no-unused-vars */
import { useModel } from "umi";
import { ConfigProvider } from "antd";
import React, { useState, useEffect, useRef } from "react";
import styles from "./index.less";
import {
  DndContext,
  KeyboardSensor,
  PointerSensor,
  TouchSensor,
  useSensor,
  useSensors,
  DragOverlay,
} from "@dnd-kit/core";
import { arrayMove, sortableKeyboardCoordinates } from "@dnd-kit/sortable";
import Draggable from "@/components/DragContainer/contain";
import config from "../../layouts/config";
import FormDom from "@/components/DragContainer/formdom";
import { ProForm } from "@ant-design/pro-components";
import { generateRandomString } from "@/utils/fns";
import Body from "./body";

export default function Layout() {
  const [active, setActive] = useState(null);
  const [dty, setDty] = useState(null);

  // 当前拖拽节点ref
  const currentDragFieldRef = useRef();

  // 占位ref
  const spacerInsertedRef = useRef();

  const {
    initialState: { formControls, formConfig, auto },
    setInitialState,
  } = useModel("@@initialState");

  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 1,
      },
    }),
    useSensor(TouchSensor, {
      activationConstraint: {
        distance: 1,
      },
    }),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
      activationConstraint: {
        distance: 1,
      },
    })
  );

  //变更布局调整
  useEffect(() => {
    // { xs: 24, sm: 24, md: 12, lg: 12, xl: 12, xxl: 12 }
    if (auto) {
      setInitialState((s) => ({
        ...s,
        formConfig: {
          ...s.formConfig,
          colProps: { xs: 24, sm: 24, md: 12, lg: 12, xl: 12, xxl: 12 },
        },
        activeItem: {
          ...s.activeItem,
          colProps: { xs: 24, sm: 24, md: 12, lg: 12, xl: 12, xxl: 12 },
        },
      }));
    } else {
      setInitialState((s) => ({
        ...s,
        formConfig: {
          ...s.formConfig,
          colProps: { span: 12 },
        },
        activeItem: {
          ...s.activeItem,
          colProps: { span: 12 },
        },
      }));
    }
  }, [auto]);

  return (
    <ConfigProvider theme={{ cssVar: true }}>
      <div className={styles.navs}>
        <DndContext
          sensors={sensors}
          onDragStart={handleDragStart}
          onDragEnd={handleDragEnd}
          onDragOver={handleDragOver}
        >
          <Body />
          <DragOverlay dropAnimation={false}>
            {active ? (
              dty?.name ? (
                <ProForm submitter={false} layout={formConfig?.layout}>
                  <FormDom control={dty} />
                </ProForm>
              ) : (
                <Draggable type={active} />
              )
            ) : null}
          </DragOverlay>
        </DndContext>
      </div>
    </ConfigProvider>
  );

  function getData(prop) {
    return prop?.data?.current ?? {};
  }

  function createSpacer(extra) {
    return {
      ...extra,
      type: "spacer",
      name: "spacer",
    };
  }

  //清空状态
  function cleanUp() {
    currentDragFieldRef.current = null;
    spacerInsertedRef.current = false;
  }

  function handleDragStart({ active }) {
    setActive(active.id);
    const activeData = getData(active);

    // 是否从sidebar拖拽过来
    if (!activeData.fromSidebar) {
      let item = active.data?.current?.sortable?.items?.find(
        (it) => it.name === active.id
      );
      setDty(item);
      //设置当前拖拽的节点数据ref
      currentDragFieldRef.current = activeData.control;
      //排序开始拖拽时的占位spacer
      setInitialState((s) => {
        let curcontrols = JSON.parse(JSON.stringify(s.formControls));
        //加入占位符
        curcontrols.splice(
          activeData.index,
          1,
          createSpacer({ ...activeData.control, id: active.id })
        );
        console.log(curcontrols);
        return {
          ...s,
          formControls: curcontrols,
        };
      });
    } else {
      setDty(null);
      //设置新增初始数据
      currentDragFieldRef.current = {
        type: active.id,
        name: generateRandomString(8),
        label: config[active.id]?.deftitle,
        required: false,
        colProps: formConfig?.colProps,
      };
    }
  }

  function handleDragOver(e) {
    const { active, over } = e;
    const activeData = getData(active);

    if (activeData.fromSidebar) {
      debugger;
      const overData = getData(over);
      if (!spacerInsertedRef.current) {
        const spacer = createSpacer({
          id: active.id + "-spacer",
          label: config[active.id]?.deftitle,
          colProps: formConfig?.colProps,
        });

        setInitialState((s) => {
          let curcontrols = JSON.parse(JSON.stringify(s.formControls));
          //加入占位符
          if (!curcontrols.length) {
            curcontrols.push(spacer);
          } else {
            const nextIndex =
              overData.index > -1 ? overData.index : curcontrols.length;

            curcontrols.splice(nextIndex, 0, spacer);
          }
          spacerInsertedRef.current = true;
          return {
            ...s,
            formControls: curcontrols,
          };
        });
      } else if (!over) {
        // 未放置去除占位符
        setInitialState((s) => {
          let curcontrols = JSON.parse(JSON.stringify(s.formControls));
          //加入占位符
          curcontrols = curcontrols.filter((f) => f.type !== "spacer");
          return {
            ...s,
            formControls: curcontrols,
          };
        });
        spacerInsertedRef.current = false;
      } else {
        setInitialState((s) => {
          let curcontrols = JSON.parse(JSON.stringify(s.formControls));

          const spacerIndex = curcontrols.findIndex(
            (f) => f.id === active.id + "-spacer"
          );

          const nextIndex =
            overData.index > -1 ? overData.index : curcontrols.length - 1;

          if (nextIndex === spacerIndex) {
            return {
              ...s,
            };
          }

          return {
            ...s,
            formControls: arrayMove(curcontrols, spacerIndex, overData.index),
          };
        });
      }
    }
  }

  function handleDragEnd(event) {
    const { over } = event;
    setActive(null);

    if (over) {
      let nextField = currentDragFieldRef.current;
      if (nextField) {
        const overData = getData(over);
        //替换占位符数据为 currentDragFieldRef 的数据
        setInitialState((s) => {
          let curcontrols = JSON.parse(JSON.stringify(s.formControls));
          //加入占位符
          const spacerIndex = curcontrols.findIndex((f) => f.type === "spacer");
          curcontrols.splice(spacerIndex, 1, nextField);

          curcontrols = arrayMove(
            curcontrols,
            spacerIndex,
            overData.index || 0
          );

          return {
            ...s,
            formControls: curcontrols,
          };
        });
      }
    } else {
      setInitialState((s) => {
        let curcontrols = JSON.parse(JSON.stringify(s.formControls));
        //加入占位符
        curcontrols = curcontrols.filter((f) => f.type !== "spacer");
        return {
          ...s,
          formControls: curcontrols,
        };
      });
    }
    cleanUp();
  }
}

/*<ul>
  <li>
    <Link to="/">Home</Link>
  </li>
  <li>
    <Link to="/docs">Docs</Link>
  </li>
  <li>
    <a href="https://github.com/umijs/umi">Github</a>
  </li>
</ul> */
